package com.hula.loan4u.view;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.hula.loan4u.R;
import com.hula.loan4u.utils.LogUtil;

import butterknife.BindView;
import butterknife.ButterKnife;


public class AppWebView extends RelativeLayout {
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.webView)
    WebView webView;
    ViewGroup rootView;
    private NewsWebViewCallBack callBack;

    public AppWebView(Context context) {
        this(context, null);
    }

    public AppWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        rootView = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.layout_progress_webview, this, true);
        ButterKnife.bind(this);
        initView();
        setListner();
    }

    public void setNewsWebViewCallBack(NewsWebViewCallBack callBack) {
        this.callBack = callBack;
    }

    private void initView() {
        try {
            WebSettings settings = webView.getSettings();
            settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
            settings.setBuiltInZoomControls(false);
            settings.setDomStorageEnabled(true);
            settings.setAppCacheEnabled(true);
            settings.setDefaultTextEncodingName("UTF-8");
            settings.setGeolocationEnabled(true);
            settings.setJavaScriptEnabled(true);
        } catch (Exception e) {
            LogUtil.printeException(e);
        }
    }

    private void setListner() {
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtil.i("AppWebView", "shouldOverrideUrlLoading=====" + url);
                if (url.startsWith("http")) {
                    webView.loadUrl(url);
                } else {
                    Uri uri = Uri.parse(url);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    getContext().startActivity(intent);
                }
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                progressBar.setVisibility(View.VISIBLE);
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                LogUtil.i("AppWebView", "onPageFinished=====" + url);
                progressBar.setVisibility(View.GONE);
                if (callBack != null) {
                    callBack.loadSuccess();
                }
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    progressBar.setVisibility(View.GONE);
                    if (callBack != null) {
                        callBack.loadSuccess();
                    }
                } else {
                    progressBar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }
        });
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                try {
                    Uri uri = Uri.parse(url);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    getContext().startActivity(intent);
                } catch (Exception e) {
                    LogUtil.printeException(e);
                }
            }
        });
    }

    public void loadUrl(String url) {
        webView.loadUrl(url);
    }

    public void loadData(String htmlData) {
        webView.loadDataWithBaseURL(null, htmlData, "text/html", "UTF-8", null);
    }

    public void destoryWebView() {
        rootView.removeView(webView);
        if (webView != null) {
            webView.loadUrl("about:blank");
            webView.destroy();
        }
        removeView(rootView);
    }

    public String getTitle() {
        return webView.getTitle();
    }

    public boolean back() {
        if (webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return false;
    }

    public interface NewsWebViewCallBack {
        void loadSuccess();
    }
}
